package com.xyw.code.controller;

import com.xyw.code.constant.XConstant;
import com.xyw.code.entity.SysRole;
import com.xyw.code.entity.SysUser;
import com.xyw.code.log.SysLog;
import com.xyw.code.security.XUser;
import com.xyw.code.security.util.JwtUtil;
import com.xyw.code.service.ISysDeptService;
import com.xyw.code.service.ISysRoleService;
import com.xyw.code.service.ISysUserService;
import com.xyw.code.utils.CaptchaUtil;
import com.xyw.code.utils.Result;
import io.swagger.annotations.Api;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * Created by xuyiwei on 2019/7/30.
 */
@Api(value = "主页模块")
@RestController
public class IndexController {

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private ISysDeptService deptService;

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 生成验证码
     *
     * @param response
     * @param request
     * @throws ServletException
     * @throws IOException
     */
    @GetMapping("/captcha.jpg")
    public Result<Map> captcha(HttpServletResponse response, HttpServletRequest request) throws IOException {
        // 生成图片验证码
        BufferedImage image = CaptchaUtil.createImage();
        // 生成文字验证码
        String randomText = CaptchaUtil.drawRandomText(image);
        // 保存到验证码到 redis 有效期两分钟
        String uuid = UUID.randomUUID().toString().replaceAll("-","");
        redisTemplate.opsForValue().set(XConstant.X_IMAGE_SESSION_KEY+"_"+uuid, randomText.toLowerCase(),
                2, TimeUnit.MINUTES);

        // 生成图片验证码
        ByteArrayOutputStream outputStream =  new ByteArrayOutputStream();

        ImageIO.write(image, "jpeg", outputStream);
        // 生成captcha的token
        Map<String, Object> map = new HashMap();
        // 对字节数组Base64编码
        BASE64Encoder encoder = new BASE64Encoder();
        map.put("img", encoder.encode(outputStream.toByteArray()));
        map.put("uuid",  uuid);
        return Result.ok(map);
    }

    /**
     * 用户详情
     * @return
     */
    @RequestMapping(value = "/info")
    public Result<Map<String,Object>> info(HttpServletRequest request) {
        XUser securityUser = jwtUtil.getUserFromToken(request);
        //得到用户
        SysUser user = userService.getById(securityUser.getUserId());

        Map<String, Object> map = new HashMap<>();
        List<String> list = roleService.selectRoleListByUserId(securityUser.getUserId()).stream()
                .filter(n-> StringUtils.isNotBlank(n.getRoleName())).map(SysRole::getRoleCode).collect(Collectors.toList());
        String deptName = deptService.selectDeptNameByDeptId(user.getDeptId());

        map.put("roles", list);
        map.put("avatar", user.getAvatar());
        map.put("nickName", user.getNickName());
        map.put("name", user.getUsername());
        map.put("phone", user.getPhone());
        map.put("email", user.getEmail());
        map.put("deptName", deptName);

        map.put("introduction","I am a "+user.getUsername());
        return Result.ok(map);
    }

    /**
     * 登录
     *
     * @param map
     * @return
     */
    @SysLog(descrption = "登录日志")
    @RequestMapping(value = "/login")
    public Result<String> login(@RequestBody Map<String, String> map, HttpServletRequest request) {
        return Result.ok(userService.login(map.get("username"), map.get("password"), map.get("captcha"),map.get("captchauuid"), request));
    }


    /**
     * 其实只要jwt 前端清除token即可
     **/
    @RequestMapping("/logout")
    public String logout(){
        return "success";
    }
}
